import { createPersistStore, BaseState } from './index'
import { 
  DragItem, 
  DropResult,
  ChapterDragItem,
  CharacterDragItem
} from '@/types/drag-drop'
import { 
  FormattedContent, 
  formatDragContent 
} from '@/services/dragContentFormatter'
import { nanoid } from 'nanoid'
import { useUIStore } from './uiStore'

// 临时拖拽项目
export interface DragDropSession {
  id: string;
  startTime: string;
  items: DragItem[];
  source: string;
}

// 拖拽状态
interface DragDropState extends BaseState {
  // 当前拖拽会话
  currentSession: DragDropSession | null;
  // 已放置但未处理的内容
  droppedItems: FormattedContent[];
  // 拖拽历史
  dragHistory: DragDropSession[];
  
  // 操作函数
  startDrag: (items: DragItem[], source: string) => void;
  endDrag: (dropped: boolean) => void;
  handleDrop: (result: DropResult) => void;
  removeDroppedItem: (index: number) => void;
  clearDroppedItems: () => void;
  
  // 转换为AI助手内容
  dragItemToAttachment: (item: DragItem) => any;
}

// 初始状态
const initialState = {
  currentSession: null,
  droppedItems: [],
  dragHistory: [],
  isLoading: false,
  error: null
};

export const useDragDropStore = createPersistStore<DragDropState>(
  'drag-drop',
  initialState as any,
  (set, get) => ({
    ...initialState,
    
    startDrag: (items, source) => {
      const session: DragDropSession = {
        id: nanoid(),
        startTime: new Date().toISOString(),
        items,
        source
      };
      
      set({ currentSession: session });
      
      // 更新UI状态
      useUIStore.getState().setDragging(true, source);
    },
    
    endDrag: (dropped) => {
      const { currentSession } = get();
      
      if (currentSession) {
        // 添加到历史记录
        set(state => ({
          dragHistory: [...state.dragHistory, currentSession],
          currentSession: null
        }));
      }
      
      // 更新UI状态
      useUIStore.getState().setDragging(false);
    },
    
    handleDrop: (result) => {
      if (result.success) {
        const formattedItems = formatDragContent(result.items);
        
        set(state => ({
          droppedItems: [...state.droppedItems, ...formattedItems]
        }));
      }
    },
    
    removeDroppedItem: (index) => {
      set(state => ({
        droppedItems: state.droppedItems.filter((_, i) => i !== index)
      }));
    },
    
    clearDroppedItems: () => {
      set({ droppedItems: [] });
    },
    
    dragItemToAttachment: (item) => {
      const attachment = {
        id: nanoid(),
        name: item.name
      };
      
      switch (item.type) {
        case 'chapter':
          const chapterItem = item as ChapterDragItem;
          return {
            ...attachment,
            type: 'chapter',
            content: chapterItem.data,
            previewText: chapterItem.data.content.length > 50 
              ? `${chapterItem.data.content.substring(0, 50)}...` 
              : chapterItem.data.content
          };
          
        case 'character':
          const characterItem = item as CharacterDragItem;
          return {
            ...attachment,
            type: 'character',
            content: characterItem.data,
            previewText: characterItem.data.description 
              ? (characterItem.data.description.length > 50 
                ? `${characterItem.data.description.substring(0, 50)}...` 
                : characterItem.data.description)
              : '无描述'
          };
          
        default:
          return {
            ...attachment,
            type: item.type,
            content: item.data,
            previewText: '内容预览不可用'
          };
      }
    }
  })
); 